package io.babystar.modules.business.controller;

import java.util.*;

import io.babystar.modules.app.dto.StudentDayCourseDateDto;
import io.babystar.modules.business.entity.CourseDateEntity;
import io.babystar.modules.business.service.CourseDateService;
import io.babystar.modules.sys.controller.AbstractController;
import io.babystar.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.babystar.modules.business.entity.CourseEntity;
import io.babystar.modules.business.service.CourseService;
import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.R;



/**
 * 
 *
 * @author jeson
 * @email 574197743@qq.com
 * @date 2021-03-23 20:03:34
 */
@RestController
@RequestMapping("business/course")
public class CourseController extends AbstractController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseDateService courseDateService;


    /**
     * 查询课程的所有课程时间-课程页
     *
     * @param id
     * @return
     */
    @RequestMapping("/getCourseTime")
    public R getCourseTime(int id) {
        List<StudentDayCourseDateDto> list = courseDateService.getCourseTimes(id);
        List<Map<String, Object>> lists = new ArrayList<>();
        int i = 0;
        for (CourseDateEntity map : list) {
            String time = map.getCourseWeekZh() + " " + map.getStartTime();
            Map<String, Object> mapA = new HashMap<>();
            Map<String, Object> mapB = new HashMap<>();
            mapB.put("courseweekname", map.getCourseWeekZh());
            mapB.put("id", map.getCourseWeekEn());
            mapA.put("ids", map.getId());
            mapA.put("courseweek", mapB);
            mapA.put("courseweektime", map.getStartTime());
            lists.add(i, mapA);
            i++;
        }
        return R.ok().put("courseTime", lists);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:course:list")
    public R list(@RequestParam Map<String, Object> params){
        SysUserEntity user = this.getUser();
        params.put("organizeid", user.getBusinessId());
        PageUtils page = courseService.queryPageCourse(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("business:course:info")
    public R info(@PathVariable("id") Long id){
		CourseEntity course = courseService.getById(id);

        return R.ok().put("course", course);
    }


    /**
     * 保存
     */
    @Transactional
    @RequestMapping("/save")
    @RequiresPermissions("business:course:save")
    public R save(@RequestBody CourseEntity course) {
        //CourseEntity courses = new CourseEntity();
        System.out.println("看看接收到的课程参数1111111111111111"+course.getPic2()+"----"+course.getPic());
        try {
            //CopyPropertiesUntil.copyProperties(courses, course);
            //BeanUtils.copyProperties(courses,course);
            courseService.save(course);
            int id = Integer.parseInt(course.getId().toString());
            List<Map<String, Object>> coursetime = course.getCoursetime();
            for (int i = 0; i < coursetime.size(); i++) {
                Map<String, Object> jsonObject = coursetime.get(i);
                String courseStarttime = jsonObject.get("courseweektime").toString();
                Map<String, Object> courseweek = (Map<String, Object>) jsonObject.get("courseweek");
                String courseweekzh = courseweek.get("courseweekname").toString();
                String courseweeken = courseweek.get("id").toString();
                CourseDateEntity courseDateEntity = new CourseDateEntity();
                courseDateEntity.setCourseId(id);
                courseDateEntity.setCourseWeekEn(courseweeken);
                courseDateEntity.setCourseWeekZh(courseweekzh);
                courseDateEntity.setStartTime(courseStarttime);
                courseDateEntity.setCreateTime(new Date());
                courseDateService.save(courseDateEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @Transactional
    @RequestMapping("/update")
    @RequiresPermissions("business:course:update")
    public R update(@RequestBody CourseEntity course) {
        try {
            courseService.updateById(course);

            Map<String, Object> oldCourseMap = new HashMap<>();
            oldCourseMap.put("course_id", course.getId().intValue());
            List<CourseDateEntity> oldCourseLIist = courseDateService.listByMap(oldCourseMap);
            List<String> oldIdList = new ArrayList<>();
            for (CourseDateEntity courseDateEntity : oldCourseLIist) {
                oldIdList.add(courseDateEntity.getId().toString());
            }
            List<Map<String, Object>> coursetime = course.getCoursetime();
            // 新增课程时间：若为编辑，则修改update；若为新加，则新增课时。
            for (Map newCourseMap : coursetime) {
                if (newCourseMap.containsKey("ids") && StringUtils.isNotBlank(newCourseMap.get("ids").toString())) {
                    oldIdList.remove(newCourseMap.get("ids").toString());
                    CourseDateEntity courseDateEntity = new CourseDateEntity();
                    String courseStarttime = newCourseMap.get("courseweektime").toString();
                    Map<String, Object> courseweek = (Map<String, Object>) newCourseMap.get("courseweek");
                    String courseweekzh = courseweek.get("courseweekname").toString();
                    String courseweeken = courseweek.get("id").toString();
                    courseDateEntity.setId(Long.parseLong(newCourseMap.get("ids").toString()));
                    courseDateEntity.setCourseWeekEn(courseweeken);
                    courseDateEntity.setCourseWeekZh(courseweekzh);
                    courseDateEntity.setStartTime(courseStarttime);
                    courseDateEntity.setUpdateTime(new Date());
                    courseDateService.updateById(courseDateEntity);
                } else {
                    CourseDateEntity courseDateEntity = new CourseDateEntity();
                    String courseStarttime = newCourseMap.get("courseweektime").toString();
                    Map<String, Object> courseweek = (Map<String, Object>) newCourseMap.get("courseweek");
                    String courseweekzh = courseweek.get("courseweekname").toString();
                    String courseweeken = courseweek.get("id").toString();
                    courseDateEntity.setCourseId(course.getId().intValue());
                    courseDateEntity.setCourseWeekEn(courseweeken);
                    courseDateEntity.setCourseWeekZh(courseweekzh);
                    courseDateEntity.setStartTime(courseStarttime);
                    courseDateService.save(courseDateEntity);
                }
            }
            // 删除编辑后删除的课时
            for (String id : oldIdList) {
                courseDateService.removeById(Long.parseLong(id));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("business:course:delete")
    public R delete(@RequestBody Long[] ids){
		courseService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 查询学生所选课程的所有课程时间-学生页
     */
    @RequestMapping("/getCourseTimes")
    public R getCourseTimes(String id) {
        List<StudentDayCourseDateDto> list = courseDateService.getCourseTimes(Integer.parseInt(id));
        List<Map<String, Object>> lists = new ArrayList<>();
        int i = 0;
        for (CourseDateEntity map : list) {
            String time = map.getCourseWeekZh() + " " + map.getStartTime();
            Map<String, Object> mapA = new HashMap<>();
            mapA.put("courseTimes", time);
            mapA.put("id", map.getId());
            lists.add(i, mapA);
            i++;
        }
        return R.ok().put("courseTimes", lists);
    }

    /**
     * 校验已被选课的课程不可进行修改和删除操作
     *
     * @param courseId
     * @return
     */
    @RequestMapping("/qureyCourseInfo")
    public R qureyCourseInfo(Integer courseId) {
        Integer count = 0;
        try {
            count = courseService.qureyCourseInfo(courseId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("count", count);
    }

}
